//
//  HMUserAccount.swift
//  Weibo12
//
//  Created by HM on 15/12/29.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit

class HMUserAccount: NSObject, NSCoding {

    // 用户头像地址（大图），180×180像素
    var avatar_large: String?
    // 用户昵称
    var screen_name: String?
    // 用户的 UID
    var uid: String?
    // 过期时间：相对于获取回来的那一刻开始计算，expires_in 这么多秒之后过期
    // 过期时间怎么算，当 设置 expires_in 的时候，拿着当前时间加上 expires_in 秒之后的那个新时间就是过期的时间
    var expires_in: NSTimeInterval = 0 {
        
        didSet{
            // 取到当前时间加上 expires_in 这么多秒之后的一新时间，就是过期时间
            expiresDate = NSDate().dateByAddingTimeInterval(expires_in)
        }
    }
    
    var expiresDate: NSDate?
    // 访问令牌
    var access_token: String?
    // 过期时间
    var remind_in: String?
    
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    // 归档
    func encodeWithCoder(encoder: NSCoder) {
        encoder.encodeObject(avatar_large, forKey: "avatar_large")
        encoder.encodeObject(screen_name, forKey: "screen_name")
        encoder.encodeObject(uid, forKey: "uid")
        encoder.encodeObject(expiresDate, forKey: "expiresDate")
        encoder.encodeObject(access_token, forKey: "access_token")
        encoder.encodeObject(remind_in, forKey: "remind_in")
    }
    
    // 解档
    required init?(coder decoder: NSCoder) {
        avatar_large = decoder.decodeObjectForKey("avatar_large") as? String
        screen_name = decoder.decodeObjectForKey("screen_name") as? String
        uid = decoder.decodeObjectForKey("uid") as? String
        expiresDate = decoder.decodeObjectForKey("expiresDate") as? NSDate
        access_token = decoder.decodeObjectForKey("access_token") as? String
        remind_in = decoder.decodeObjectForKey("remind_in") as? String
    }
    
    // 重写 description
    override var description: String {
        let keys = ["uid", "expires_in", "access_token", "remind_in", "avatar_large", "screen_name"]
        return dictionaryWithValuesForKeys(keys).description
    }
}
